package vn.com.mybudget.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.*;

import vn.com.mybudget.bo.AccountBO;
import vn.com.mybudget.common.CommonUtil;
import vn.com.mybudget.entities.Account;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class BaseController extends HttpServlet {
	protected String plainData = "";
	String action = "";
	protected HttpServletRequest currentRequest;
	protected HttpServletResponse currentResponse;
	protected HttpSession session;
	protected PrintWriter printer;
	protected UserService _userService;
	protected User _currentUser;
	protected Account _currentAccount;

	protected void processRequest() throws IllegalAccessException,
			IllegalArgumentException, NoSuchMethodException, SecurityException,
			IOException {
		throw new UnsupportedOperationException(
				"Please Implement processRequest()");
	}

	// <editor-fold defaultstate="collapsed"
	// desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PreProcess(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PreProcess(request, response);
	}

	private void PreProcess(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		currentRequest = request;
		currentResponse = response;
		printer = currentResponse.getWriter();
		_userService = UserServiceFactory.getUserService();
		_currentUser = _userService.getCurrentUser();

		// Get data from client
		plainData = "";
		if (request.getHeader("data") != null) {
			plainData = request.getHeader("data").toString();
		}
		if (plainData == null) {
			plainData = "";
		}
		if (plainData == "") {
			if (request.getParameter("data") != null) {
				plainData = request.getParameter("data").toString();
			}
		}
		if (plainData != null) {
			plainData = plainData.replace("\"", "");
		}
		if (plainData != null) {
			plainData = plainData.replace("\"", " ");
			plainData = plainData.trim();
		}

		// Get action from client
		action = request.getHeader("action") == null ? request
				.getParameter("action") : request.getHeader("action");
		// If client do not pass action, set it to default value Index
		action = action == null || action == "" ? "index" : action;
		// If action is not exist, redirect to root

		// Set session variable
		currentRequest.getSession().setAttribute("LogoutUrl",
				_userService.createLogoutURL("https://accounts.google.com/Logout"));
		currentRequest.getSession().setAttribute("LogInUrl",
				_userService.createLoginURL("/mybudget?action=index"));
		CommonUtil.currentPathContext = currentRequest.getRealPath("/");

		if (_currentUser != null) {
			if (currentRequest.getSession().getAttribute("email") != null) {
				if (!_currentUser.getEmail().equalsIgnoreCase(
						currentRequest.getSession().getAttribute("email")
								.toString())) {
					currentRequest.getSession().removeAttribute("email");
				}
			}
		}

		// Check user account exist and set usersession
		if (currentRequest.getSession().getAttribute("email") == null) {
			String qt = currentRequest.getQueryString();
			// Require login
			if (qt == null)
				qt = "";
			if (_currentUser == null
					&& (!qt.contains("Login") && !qt.contains("login") && !qt.contains("welcome"))) {
				currentResponse.sendRedirect("/mybudget?action=welcome");
			} else {
				if (_currentUser != null) {
					AccountBO abo = new AccountBO();
					_currentAccount = abo.getAccountByEmail(_currentUser);
					String username = _currentAccount.getEmail().toUpperCase();
					username = username.substring(0, username.indexOf('@'))
							.toUpperCase();
					currentRequest.getSession().setAttribute("username",
							username);
					currentRequest.getSession().setAttribute("email",
							_currentAccount.getEmail().toUpperCase());
					/*
					 * currentRequest.getSession().setAttribute("currentAccount",
					 * _currentAccount);
					 */
				}
			}

		} else {
			if (_currentAccount == null) {
				_currentAccount = (Account) currentRequest.getSession()
						.getAttribute("currentAccount");
			}
		}

		if (_currentUser != null) {
			AccountBO abo = new AccountBO();
			_currentAccount = abo.getAccountByEmail(_currentUser);
		}

		// Execute request
		if (this.action != "") {
			try {
				processRequest();
			} catch (Exception ex) {
				printer.write(ex.toString());
			}
		} else {
			printer.println(getServletInfo());
		}
	}

}